"""
f(x, y) = x^2 + 2y^2
用梯度下降算法求出其最低点，学习率为0.01，其损失函数为均方差损失函数、
要求绘制其原函数图并标记出最低点和梯度路径、损失函数图并标记其最小损失点。
"""
import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':
    # 起始参数
    x = 10
    y = 10
    learning_rate = 0.01
    points = []
    print(f'当前位置：({x}, {y})')
    for i in range(1000):
        # 更新位置
        x = x - learning_rate * 2 * x
        y = y - learning_rate * 4 * y
        if x <= 0 and y <= 0:
            break
        print(f'当前位置：({x:.5f}, {y:.5f})')
        z = x ** 2 + 2 * y ** 2
        points.append([x, y, z])

    # 创建一个网格
    x = np.linspace(-10, 10, 400)
    y = np.linspace(-10, 10, 400)
    x, y = np.meshgrid(x, y)
    z = x ** 2 + 2 * y ** 2
    # 绘制曲面图
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(x, y, z, cmap='viridis', alpha=0.7)

    # 在图中绘制特定的点
    for p in points:
        ax.scatter(p[0], p[1], p[2], color='r', s=50)  # 红色点表示特定的点

    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')
    ax.set_zlabel('Z axis')
    ax.set_title('Surface Plot of f(x, y) = x^2 + 2y^2')

    plt.show()
